import React, { useState } from 'react';
import { View, StyleSheet, Text, TouchableOpacity, Platform } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import * as AppleAuthentication from 'expo-apple-authentication';
import { StatusBar } from 'expo-status-bar';
import { useNavigation } from '@react-navigation/native';
import { Ionicons } from '@expo/vector-icons';
import AppHeader from '../components/AppHeader';
import PrimaryButton from '../components/PrimaryButton';
import InputField, { EyeToggle } from '../components/InputField';
import { Colors } from '../constants/colors';
import { authService, AuthManager } from '../services';
import { showError, showSuccess } from '../utils/webAlert';
import { GoogleAuthWrapper } from '../utils/googleAuthWrapper';


export default function SignUpScreen() {
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPwd, setShowPwd] = useState(false);
  const [loading, setLoading] = useState(false);
  const nav = useNavigation<any>();



  // 验证输入
  const validateInputs = () => {
    if (!username.trim()) {
      showError('請輸入用戶名');
      return false;
    }

    if (username.trim().length < 2 || username.trim().length > 20) {
      showError('用戶名長度應在2-20個字符之間');
      return false;
    }

    if (!email.trim()) {
      showError('請輸入電郵地址');
      return false;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      showError('請輸入有效的電郵地址');
      return false;
    }

    if (!password.trim()) {
      showError('請輸入密碼');
      return false;
    }

    if (password.trim().length < 6 || password.trim().length > 20) {
      showError('密碼長度應在6-20個字符之間');
      return false;
    }

    return true;
  };

  // 檢查用戶名是否可用
  const checkUsername = async (userName: string) => {
    try {
      const result = await authService.checkUsername(userName);
      return !result.exists;
    } catch (error) {
      console.error('檢查用戶名失敗:', error);
      return false;
    }
  };

  // 檢查電郵是否可用
  const checkEmail = async (emailAddr: string) => {
    try {
      const result = await authService.checkEmail(emailAddr);
      return !result.exists;
    } catch (error) {
      console.error('檢查電郵失敗:', error);
      return false;
    }
  };

  // 處理註冊
  const handleRegister = async () => {
    console.log('註冊按鈕被點擊');

    if (!validateInputs()) {
      console.log('表單驗證失敗');
      return;
    }

    console.log('開始註冊流程');
    setLoading(true);
    try {
      // 檢查用戶名是否可用
      const isUsernameAvailable = await checkUsername(username.trim());
      if (!isUsernameAvailable) {
        showError('用戶名已存在，請選擇其他用戶名');
        return;
      }

      // 檢查電郵是否可用
      const isEmailAvailable = await checkEmail(email.trim());
      if (!isEmailAvailable) {
        showError('電郵已被註冊，請使用其他電郵');
        return;
      }

      // 執行註冊
      const result = await authService.register({
        userName: username.trim(),
        email: email.trim(),
        password: password.trim(),
      });

      // 保存token
      if (result.token) {
        await AuthManager.setToken(result.token);
        console.log('註冊Token保存完成:', result.token);
      }

      showSuccess(result.message || '註冊成功', () => {
        // 使用setTimeout确保在Web端也能正确跳转
        setTimeout(() => {
          nav.reset({
            index: 0,
            routes: [{ name: 'RoleSelect' }],
          });
        }, 100);
      });
    } catch (error: any) {
      console.error('註冊失敗:', error);
      showError(error.message || '註冊過程中發生錯誤，請稍後重試');
    } finally {
      setLoading(false);
    }
  };

  // Apple注册处理
  const handleAppleSignUp = async () => {
    setLoading(true);
    try {
      // 检查Apple登录是否可用
      const isAvailable = await AppleAuthentication.isAvailableAsync();
      if (!isAvailable) {
        showError('Apple註冊在此設備上不可用');
        return;
      }

      // 执行Apple登录
      const credential = await AppleAuthentication.signInAsync({
        requestedScopes: [
          AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
          AppleAuthentication.AppleAuthenticationScope.EMAIL,
        ],
      });

      console.log('Apple註冊憑證:', credential);

      // 發送到後端（登錄和註冊是同一個API）
      const result = await authService.appleLogin({
        idToken: credential.identityToken || '',
      });

      // 保存token
      if (result.token) {
        await AuthManager.setToken(result.token);
        console.log('Apple註冊Token保存完成:', result.token);
      }

      showSuccess(result.message || 'Apple註冊成功', () => {
        setTimeout(() => {
          nav.reset({
            index: 0,
            routes: [{ name: 'RoleSelect' }],
          });
        }, 100);
      });
    } catch (error: any) {
      console.error('Apple註冊失敗:', error);
      if (error.code === 'ERR_CANCELED') {
        // 用户取消，不显示错误
        return;
      }
      showError(error.message || 'Apple註冊失敗');
    } finally {
      setLoading(false);
    }
  };

  // Google注册处理
  const handleGoogleSignUp = async () => {
    setLoading(true);
    try {
      // 使用包装器处理Google登錄
      const result = await GoogleAuthWrapper.signIn() as any;

      // 发送到后端（登录和注册是同一个API）
      const authResult = await authService.googleLogin({
        idToken: result.idToken,
      });

      // 保存token
      if (authResult.token) {
        await AuthManager.setToken(authResult.token);
        console.log('Google注册Token保存完成:', authResult.token);
      }

      showSuccess(authResult.message || 'Google註冊成功', () => {
        setTimeout(() => {
          nav.reset({
            index: 0,
            routes: [{ name: 'RoleSelect' }],
          });
        }, 100);
      });
    } catch (error: any) {
      console.error('Google註冊失敗:', error);
      if (error.message === '用户取消') {
        // 用户取消，不显示错误
        return;
      }
      showError(error.message || 'Google註冊失敗');
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar style="light" backgroundColor="#f97316" />
      <AppHeader title="註冊" showBack variant="plain" largeTitle />

      <View style={styles.content}>
        {/* 社交註冊 */}
        <View style={{ marginTop: 8 }}>
          {Platform.OS === 'ios' && (
          <TouchableOpacity
            activeOpacity={0.9}
            style={[styles.socialBtn, { opacity: loading ? 0.6 : 1 }]}
            onPress={handleAppleSignUp}
            disabled={loading}
          >
            <Ionicons name="logo-apple" size={18} color={Colors.black} style={{ marginRight: 8 }} />
            <Text style={styles.socialBtnText}>{loading ? "註冊中..." : "Apple 註冊"}</Text>
          </TouchableOpacity>
          )}
          <TouchableOpacity
            activeOpacity={0.9}
            style={[styles.socialBtn, { marginTop: 12, opacity: loading ? 0.6 : 1 }]}
            onPress={handleGoogleSignUp}
            disabled={loading}
          >
            <Ionicons name="logo-google" size={18} color={Colors.black} style={{ marginRight: 8 }} />
            <Text style={styles.socialBtnText}>{loading ? "註冊中..." : "Google 註冊"}</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.dividerRow}>
          <View style={styles.dividerLine} />
          <Text style={styles.dividerText}>或使用電郵註冊</Text>
          <View style={styles.dividerLine} />
        </View>

        {/* Inputs */}
        <View style={{ marginTop: 12 }}>
          <InputField label="用戶名" value={username} onChangeText={setUsername} variant="card" />
        </View>

        <View style={{ marginTop: 12 }}>
          <InputField label="電郵地址" value={email} onChangeText={setEmail} keyboardType="email-address" autoCapitalize="none" variant="card" />
        </View>

        <View style={{ marginTop: 12 }}>
          <InputField label="密碼" value={password} onChangeText={setPassword} secureTextEntry={!showPwd} right={<EyeToggle visible={showPwd} onToggle={() => setShowPwd(v => !v)} />} variant="card" />
        </View>

        <PrimaryButton
          title={loading ? "註冊中..." : "完成註冊"}
          onPress={handleRegister}
          disabled={loading}
          style={{ marginTop: 12 }}
        />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: Colors.white },
  content: { paddingHorizontal: 20, paddingTop: 12 },

  socialBtn: {
    height: 56,
    borderRadius: 12,
    backgroundColor: Colors.white,
    borderWidth: 1,
    borderColor: Colors.gray[200],
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    shadowColor: Colors.black,
    shadowOpacity: 0.06,
    shadowRadius: 6,
    shadowOffset: { width: 0, height: 2 },
    elevation: 1,
  },
  socialBtnText: { fontSize: 16, color: Colors.black, fontWeight: '600' },

  dividerRow: { flexDirection: 'row', alignItems: 'center', marginVertical: 18 },
  dividerLine: { flex: 1, height: 1, backgroundColor: Colors.gray[200] },
  dividerText: { marginHorizontal: 16, color: Colors.gray[400], fontSize: 14 },

  inputGroup: { marginBottom: 12 },
  inputLabel: { color: Colors.gray[500], marginBottom: 8 },
  input: {
    minHeight: 56, // 使用minHeight而不是固定height
    borderRadius: 12,
    backgroundColor: Colors.gray[100],
    paddingHorizontal: 16,
    color: Colors.black,
    marginBottom: 0,
    fontSize: 16,
    textAlignVertical: 'center', // 安卓文本垂直居中
  },
  inputWithIcon: {
    minHeight: 56, // 使用minHeight而不是固定height
    borderRadius: 12,
    backgroundColor: Colors.gray[100],
    flexDirection: 'row',
    alignItems: 'center',
    paddingRight: 8,
    paddingLeft: 0,
    overflow: 'hidden',
  },
  iconBtn: { paddingHorizontal: 12, height: '100%', justifyContent: 'center' },
  cardWrap: {
    backgroundColor: Colors.white,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: Colors.gray[200],
    padding: 14,
    marginTop: 12,
    shadowColor: Colors.black,
    shadowOpacity: 0.03,
    shadowRadius: 4,
    shadowOffset: { width: 0, height: 2 },
  },
});

